//
//  HHCountDown.m
//  pod
//
//  Created by chun.chen on 2018/4/27.
//  Copyright © 2018年 qrh. All rights reserved.
//

#import "HHCountDown.h"
#import <BCFoundation/BCFoundationUtils.h>

static NSInteger const kHHCountDownTime = 59;

@interface HHCountDown()
/** 倒计时timer */
@property (nonatomic, strong) dispatch_source_t zh_timer;
@end

@implementation HHCountDown
//MARK: - life cycle
+ (instancetype)defaultInstance {
    static HHCountDown *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        sharedInstance.time = kHHCountDownTime;
    });
    return sharedInstance;
}

@end

@implementation UIButton (HHCountDown)

-(void)startTime:(NSInteger )time
{
    [self startTime:time withText:@"s"];
}
- (void)startTime:(NSInteger)time withText:(NSString *)text
{
    self.enabled = NO;
    __block NSInteger timeout = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if (HHCountDown.defaultInstance.zh_timer != NULL) {
        dispatch_source_cancel(HHCountDown.defaultInstance.zh_timer);
    }
    HHCountDown.defaultInstance.zh_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(HHCountDown.defaultInstance.zh_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(HHCountDown.defaultInstance.zh_timer, ^{
        if (timeout <= 0) { //倒计时结束，关闭
            dispatch_source_cancel(HHCountDown.defaultInstance.zh_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                HHCountDown.defaultInstance.zh_timer = NULL;
                self.enabled = YES;
                [self setTitle:BCLOC(@"重新获取") forState:UIControlStateNormal];
                [HHCountDown defaultInstance].time = kHHCountDownTime;
            });
        }
        else {
            NSInteger seconds = timeout % 60;
            NSString* strTime = [NSString stringWithFormat:@"%.2ld%@", (long)seconds,text];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:strTime forState:UIControlStateNormal];
                [HHCountDown defaultInstance].time --;
            });
            timeout--;
        }
    });
    dispatch_resume(HHCountDown.defaultInstance.zh_timer);
}
@end
